<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>

        div{width:100px;height:100px;position: absolute;left:0}
        .box1{top:0;background: red;}
        .box2{top:100px;background: green;}

    </style>
</head>
<body>

    <div class="box1"></div>
    <div class="box2"></div>
    
</body>
<script>

    function Drag(ele){
        this.ele = ele;
        this.addEvent();
    }
    Drag.prototype.addEvent = function(){
        const that = this;
        this.ele.onmousedown = function(eve){
            that.downE = eve || window.event;
            that.down();
        }
    }
    Drag.prototype.down = function(){
        const that = this;
        document.onmousemove = function(eve){
            that.moveE = eve || window.event;
            that.move();
        }
        document.onmouseup = function(){
            that.up();
        }
    }
    Drag.prototype.move = function(){
        this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
        this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
    }
    Drag.prototype.up = function(){
        document.onmousemove = null;
        document.onmouseup = null;
    }

    // 根据已有的拖拽功能，继承出新的拖拽
    function SmallDrag(ele){
        Drag.call(this, ele);
    }
    SmallDrag.prototype = {
        ...Drag.prototype,
        // 改写其中move方法
        move(){
            let l = this.moveE.pageX - this.downE.offsetX;
            let t = this.moveE.pageY - this.downE.offsetY;
            if(l<0) l=0;
            if(t<0) t=0;
            this.ele.style.left = l + "px";
            this.ele.style.top = t + "px";
        }
    }

    const obox1 = document.querySelector(".box1");
    const obox2 = document.querySelector(".box2");

    new Drag(obox1);
    new SmallDrag(obox2);

    
</script>
</html>